package com.meida.paotui.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ListModel;
import com.meida.common.mybatis.model.PageModel;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.system.provider.service.SysAreaService;
import com.meida.module.system.provider.service.SysDictService;
import com.meida.module.system.provider.service.SysVersionService;
import com.meida.paotui.bus.client.entity.*;
import com.meida.paotui.bus.provider.mapper.BusProfitMapper;
import com.meida.paotui.bus.provider.service.*;
import com.meida.paotui.bus.provider.service.impl.BusTradeServiceImpl;
import com.meida.paotui.bus.provider.utils.RedisGeoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@Api(tags = "业务模块")
public class BusinessController {
    @Autowired
    private SysDictService sysdictService;
    @Autowired
    private RedisGeoUtils redisGeoUtils;
    @Autowired
    private SysAreaService sysareaService;
    @Autowired
    private BusTradeServiceImpl busTradeService1;
    @Autowired
    private BusRiderService busRiderService;
    @Autowired
    private BusTradeDetailService bustradedetailService;
    @Autowired
    private BusMsgreceiveService busmsgreceiveService;
    @Autowired
    private BusFeedbackService busfeedbackService;
    @Autowired
    private SysVersionService sysversionService;
    @Autowired
    private BusCustomerService buscustomerService;
    @Autowired
    private BusGoodsorderService busgoodsorderService;
    @Autowired
    private BusProfitService busProfitService;
    @Resource
    private BusProfitMapper busProfitMapper;
    @Autowired
    private BusInvoiceinfoService businvoiceinfoservice;
    @Autowired
    private BusIdentityService identityService;
    @Autowired
    private RedissonClient redissonClient;






    private String location = "location";


    @ApiOperation(value = "发票添加", notes = "发票添加")
    @PostMapping(value = "/invoice/save")
    public ResultBody save(BusInvoiceinfo invoice,
                           @RequestParam(value = "invoiceTitle", required = false) String invoiceTitle,
                           @RequestParam(value = "invoiceType", required = false) String invoiceType,
                           @RequestParam(value = "invoiceBody", required = false) String invoiceBody,
                           @RequestParam(value = "invoiceAmount", required = false) String invoiceAmount,
                           @RequestParam(value = "consignee", required = false) String consignee,
                           @RequestParam(value = "orderId", required = false) String orderId
    ) {

        ResultBody resultBody = businvoiceinfoservice.addinvoice(invoice);
        if (resultBody.isOk()) {
            if (orderId.contains(",")) {
                String[] strings = orderId.split(",");
                for (int i = 0; i < strings.length; i++) {
                    BusGoodsorder goodsorder = busgoodsorderService.getById(strings[i]);
                    goodsorder.setIsInvoice(1);
                    goodsorder.setInvoiceId(invoice.getInvoiceId());
                    busgoodsorderService.saveOrUpdate(goodsorder);
                }
            } else {
                BusGoodsorder goodsorder = busgoodsorderService.getById(orderId);
                goodsorder.setIsInvoice(1);
                goodsorder.setInvoiceId(invoice.getInvoiceId());
                busgoodsorderService.saveOrUpdate(goodsorder);
            }
        }
        return resultBody;
    }



    @ApiOperation(value = "发票详情", notes = "发票详情")
    @PostMapping(value = "/invoice/getinvoice")
    public ResultBody getinvoice(String invoiceId) {
        BusInvoiceinfo invoice = businvoiceinfoservice.getById(invoiceId);
        return ResultBody.ok(invoice);
    }
    @ApiOperation(value = "变更发票接受邮箱", notes = "变更发票接受邮箱")
    @PostMapping(value = "/invoice/updateinvoiceemail")
    public ResultBody updateinvoiceemail(String invoiceId,String email) {
        BusInvoiceinfo invoice = businvoiceinfoservice.getById(invoiceId);
        if(FlymeUtils.isEmpty(email)){
            ResultBody.failed("邮箱不能为空");
        }
        if(FlymeUtils.isEmpty(invoice)){
            ResultBody.failed("发票不存在");
        }
        invoice.setConsignee(email);
        boolean a= businvoiceinfoservice.saveOrUpdate(invoice);
        return ResultBody.ok();
    }


    @ApiOperation(value = "开票历史", notes = "开票历史")
    @PostMapping(value = "/invoice/invoiceList")
    public ResultBody invoiceList(PageModel pageModel) {
        QueryWrapper<BusGoodsorder> query = new QueryWrapper();
        query.eq("isInvoice", 1);
        query.eq("userId", OpenHelper.getUserId());
        EntityMap ma=new EntityMap();
        ma.put("isInvoice","1");
        ma.put("userId",OpenHelper.getUserId());
        ResultBody orderList = busgoodsorderService.getOrderList(pageModel,"","1");
        return orderList;
    }

    @ApiOperation(value = "冲销", notes = "冲销")
    @PostMapping(value = "/invoice/deleteinvoice")
    public ResultBody deleteinvoice(String invoiceId) {
        ResultBody resultBody = new ResultBody();
        BusInvoiceinfo invoice = businvoiceinfoservice.getById(invoiceId);
        invoice.setStatus("-1");//冲销
        QueryWrapper<BusGoodsorder>  qw=new QueryWrapper<>();
        qw.eq("invoiceId",invoiceId);
        List<BusGoodsorder> orderList=busgoodsorderService.list(qw);
        if(orderList.size()>0){
            for (BusGoodsorder order:  orderList)
            {
                order.setInvoiceId(null);
                order.setIsInvoice(0);
                busgoodsorderService.saveOrUpdate(order);
            }
        }
        boolean a=  businvoiceinfoservice.saveOrUpdate(invoice);
        if (a) {
            resultBody.setMsg("冲销成功");
        }
        return resultBody;
    }

    @ApiOperation(value = "获取字典项", notes = "获取字典项")
    @PostMapping(value = "/sysData/getsysData")
    public ResultBody getsysData(String dicType) {
        List<EntityMap> dataMap = sysdictService.selectByCode(dicType);
        return ResultBody.ok(dataMap);
    }

    @ApiOperation(value = "获取已开通城市", notes = "获取已开通城市")
    @PostMapping(value = "/sysData/getsysArea")
    public ResultBody getsysArea(ResultBody resultbody) {
        List<EntityMap> dataMap = sysareaService.selectHotList();
        return ResultBody.ok(dataMap);
    }

    @ApiOperation(value = "添加骑手位置", notes = "添加骑手位置")
    @PostMapping(value = "redis/uploadLocation")
    public ResultBody uploadLocation(double lng, double lat)  throws  Exception{
        ResultBody resultBody = new ResultBody();
        if (FlymeUtils.isEmpty(lng) || FlymeUtils.isEmpty(lat)) {
            resultBody.code(101);
            resultBody.setMsg("参数不能为空");
        }
        String userid = String.valueOf(OpenHelper.getUserId());
//        byte[] bytes = userid.getBytes("ISO8859-1");
//        String str = new  String(bytes,"utf-8");//转化为utf-8编码
        int time = 5 * 60 * 1000;
        Boolean a = redisGeoUtils.addGeo(location, lng, lat, userid, time);
//        redissonClient.getGeo("prefix_geo_net").add(lng,lat,str);
        if (a) {
            resultBody.isOk();
            resultBody.setMsg("上传成功");
        }
        return resultBody;
    }
    @ApiOperation(value = "获取骑手位置", notes = "获取骑手位置")
    @PostMapping(value = "bfapi/getLocation")
    public ResultBody uploadLocation(String token, String userId){
        if (FlymeUtils.isEmpty(token)) {
           return  ResultBody.failed("系统标示不能为空");
        }
        if (!token.equals("e4aeVsLECTXKL4pH")) {
            return ResultBody.failed("系统标示不正确");
        }
        List<Point> point=new ArrayList<>();
        List<EntityMap> data=new ArrayList<>();
        point  = redisGeoUtils.getGeo("location", userId);
        if(FlymeUtils.isEmpty(point)){
            ResultBody body=new ResultBody();
            body.data(new ArrayList());
            body.setMsg("您要搜索的配送员不在线");
            return  body;
        }
        EntityMap pointmap=new EntityMap();
        List<Double> location=new ArrayList<>();
        location.add( point.get(0).getY());
        pointmap.put("lng",point.get(0).getX());
        pointmap.put("lat",point.get(0).getY());
        data.add(pointmap);
         return ResultBody.ok(data);
    }


    @ApiOperation(value = "获取骑手位置", notes = "获取骑手位置")
    @PostMapping(value = "redis/getlocation")
    public ResultBody getlocation(double lng, double lat) {
        if(FlymeUtils.isEmpty(lng)&&FlymeUtils.isEmpty(lat)){
            ResultBody.failed("获取不到经纬度");
        }
        GeoResults<RedisGeoCommands.GeoLocation<String>> radiusGeo = redisGeoUtils.radiusGeo(location, lng, lat, 3, Sort.Direction.ASC, 100);
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> ls = radiusGeo.getContent();
        return ResultBody.ok(ls);
    }




    @ApiOperation(value = "骑手上线", notes = "骑手上线")
    @PostMapping(value = "rider/online")
    public ResultBody online(double lng, double lat) {
        if(FlymeUtils.isEmpty(lng)&&FlymeUtils.isEmpty(lat)){
            return  ResultBody.failed("获取不到经纬度！");
        }
        ResultBody resultBody=new ResultBody();
        long userId = OpenHelper.getUserId();
        QueryWrapper<BusRider> qw = new QueryWrapper<>();
        qw.eq("userId", userId);
        BusRider rider = busRiderService.getOne(qw);
        QueryWrapper<BusIdentity>  qw_y=new QueryWrapper<>();
        qw_y.eq("userId",userId);
        BusIdentity identity=identityService.getOne(qw_y);
        if(ObjectUtils.isEmpty(identity)){
            return ResultBody.failed("您还未进行实名审核");
        }else{
            if(identity.getIsPass()!=1){
                return  ResultBody.failed("实名审核还未审核通过！");
            }
            if (ObjectUtils.isNotEmpty(rider)) {
                rider.setStatus(1);//上线
                int time = 5 * 60 * 1000;
                String userid = String.valueOf(OpenHelper.getUserId());
                Boolean a = redisGeoUtils.addGeo(location, lng, lat, userid, time);
                rider.setLat(String.valueOf(lat));
                rider.setLng(String.valueOf(lng));
                busRiderService.saveOrUpdate(rider);
            } else {
                BusRider ridernew = new BusRider();
                ridernew.setUserId(OpenHelper.getUserId());
                ridernew.setLat(String.valueOf(lat));
                ridernew.setLng(String.valueOf(lng));
                ridernew.setStatus(1);
                busRiderService.saveOrUpdate(ridernew);

            }

        }
        return resultBody;
    }

    @ApiOperation(value = "骑手下线", notes = "骑手下线")
    @PostMapping(value = "rider/downline")
    public ResultBody downline(double lng, double lat) {
        long userId = OpenHelper.getUserId();
        QueryWrapper<BusIdentity>  qw_y=new QueryWrapper<>();
        qw_y.eq("userId",userId);
        BusIdentity identity=identityService.getOne(qw_y);
        if(ObjectUtils.isEmpty(identity)){
            return  ResultBody.failed("您还未进行实名审核");
        }else{
            if(identity.getIsPass()!=1){
                return  ResultBody.failed("实名审核还未审核通过！");
            }
            QueryWrapper<BusRider> qw = new QueryWrapper<>();
            qw.eq("userId", userId);
            BusRider rider = busRiderService.getOne(qw);
            if (ObjectUtils.isNotEmpty(rider)) {
                rider.setStatus(0);//下线
                boolean a=  redisGeoUtils.removeGeo(location,String.valueOf(userId));
                if(a){
                    busRiderService.saveOrUpdate(rider);
                }
            } else {
                BusRider ridernew = new BusRider();
                ridernew.setUserId(OpenHelper.getUserId());
                ridernew.setStatus(0);
                busRiderService.saveOrUpdate(ridernew);
            }
        }
        return ResultBody.ok();
    }

    @ApiOperation(value = "获取骑手状态", notes = "获取骑手状态")
    @PostMapping(value = "rider/getriderStatus")
    public ResultBody getriderStatus() {
        long userId = OpenHelper.getUserId();
        EntityMap map = new EntityMap();
        QueryWrapper<BusRider> qw = new QueryWrapper<>();
        qw.eq("userId", userId);
        BusRider rider = busRiderService.getOne(qw);
        if (FlymeUtils.isEmpty(rider)) {
            map.put("status", 0);
        } else {
            map.put("status", rider.getStatus());
        }
        return ResultBody.ok(map);
    }

    @ApiOperation(value = "账户充值", notes = "账户充值")
    @PostMapping(value = "trade/tradeRecharge")
    public ResultBody tradeRecharge(ListModel model) {
        EntityMap map = new EntityMap();
        return  ResultBody.ok(buscustomerService.list());
    }

    @ApiOperation(value = "账户明细", notes = "账户明细")
    @PostMapping(value = "trade/tradeDeatail")
    public ResultBody tradeDeatail(PageModel pageModel) {
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isEmpty(userId)) {
            ResultBody.failed("请重新登录系统");
        }
        ResultBody resultBody = busTradeService1.pageList(pageModel, userId);
        return resultBody;
    }

    @ApiOperation(value = "骑手账户明细", notes = "骑手账户明细")
    @PostMapping(value = "profit/profitDeatail")
    public ResultBody profitDeatail(PageModel pageModel, String profitType) {
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isEmpty(userId)) {
            ResultBody.failed("请重新登录系统");
        }
        String endDate = DateUtils.formatDate();
        EntityMap resultmap = new EntityMap();
        Map map1 = new HashMap();
        map1.put("userInfoId", userId);
        map1.put("endDate", endDate);
        EntityMap map = busProfitMapper.findtotalsum(map1);
        ResultBody resultBody = busProfitService.pageList(pageModel, userId, profitType);
        if(FlymeUtils.isNotEmpty(map)){
            resultBody.put("todayMoney", map.get("totalmoney").toString());
        }else{
            resultBody.put("todayMoney",0);
        }
        return resultBody;
    }

    @ApiOperation(value = "账户提现", notes = "账户提现")
    @PostMapping(value = "trade/deposit")
    public ResultBody deposit(String bankNo, String bankName, String bankAddress, Double amount,String userName) {
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isEmpty(userId)) {
            ResultBody.failed("账户失效,重新登录");
        }
        QueryWrapper<BusProfit> qw = new QueryWrapper();
        qw.eq("userInfoId", userId);
        qw.orderByDesc("createTime");
        List<BusProfit> ProfitList = busProfitService.list(qw);
        Double a = 0.00;
        if (ProfitList.size() > 0) {
            BigDecimal balance = ProfitList.get(0).getBalance();
            if(balance.doubleValue()<amount){
                return  ResultBody.failed("提现金额大于账户余额");
            }else{
                if (balance.doubleValue() == amount) {
                    balance =BigDecimal.ZERO;
                } else {
                    a = balance.doubleValue() - amount;
                    balance =BigDecimal.valueOf(a);
                }
                BusProfit busProfit = new BusProfit();
                busProfit.setBalance(balance);
                busProfit.setProfitType(2);
                busProfit.setType("0");
                busProfit.setUserInfoId(userId);
                busProfit.setProfitWay("账户提现");
                busProfit.setProfitSum(BigDecimal.valueOf(amount));
                boolean b= busProfitService.saveOrUpdate(busProfit);
                if(b){
                    BusTradeDetail busTradeDetail = new BusTradeDetail();
                    busTradeDetail.setBankAddress(bankAddress);
                    busTradeDetail.setBankName(bankName);
                    busTradeDetail.setBankNo(bankNo);
                    busTradeDetail.setAmount(BigDecimal.valueOf(amount));
                    busTradeDetail.setUserId(OpenHelper.getUserId());
                    busTradeDetail.setUserName(userName);
                    busTradeDetail.setStatus(0);//审核前状态0 审核通过状态1
                    bustradedetailService.save(busTradeDetail);
                }
            }
        }

        return ResultBody.ok();
    }

    @ApiOperation(value = "消息列表", notes = "消息列表")
    @PostMapping(value = "message/sendMessage")
    public ResultBody sendMessage(String type, PageModel pageModel) {
        ResultBody    resultBody = busmsgreceiveService.getmsgList(pageModel, type);
        ResultBody  resultBody1 = busmsgreceiveService.getSysmsg(pageModel);
        EntityMap map = new EntityMap();
        map.put("sysData", resultBody1.getData());
        map.put("msgData", resultBody.getData());
        return ResultBody.ok(map);
    }

    @ApiOperation(value = "获取版本号", notes = "获取版本号")
    @PostMapping(value = "version/getversion")
    public ResultBody getversion(ListModel model) {
        return sysversionService.listEntityMap(model);
    }

    @ApiOperation(value = "消息详情", notes = "消息详情")
    @PostMapping(value = "message/getmessage")
    public ResultBody getmessage(String msgReceiveId) {
        if (FlymeUtils.isEmpty(msgReceiveId)) {
            ResultBody.failed("消息id不能为空");
        }
        BusMsgreceive message = busmsgreceiveService.getById(msgReceiveId);
        return ResultBody.ok(message);
    }

    @ApiOperation(value = "意见反馈", notes = "意见反馈")
    @PostMapping(value = "opinion/saveOpinion")
    public ResultBody saveOpinion(String content) {
        if (FlymeUtils.isEmpty(content)) {
            ResultBody.failed("反馈内容不为空");
        }
        BusFeedback feedback = new BusFeedback();
        feedback.setContent(content);
        feedback.setStatus(1);
        feedback.setUserId(OpenHelper.getUserId());
        feedback.setType("1");
        boolean a = busfeedbackService.save(feedback);
        return ResultBody.ok();
    }




}
